﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.DomainServices;
using NHibernate;
using SharpArch.Data.NHibernate;

namespace Magalie.Web.Classes
{
    /// <summary>
    /// DomainService de base pour NHibernate
    /// </summary>
    public class NHibernateDomainService : DomainService
    {
        public ISession Session { get; private set; }

        private ITransaction _transaction;

        [IgnoreOperation]
        public override void Initialize(DomainServiceContext context)
        {
            Session = NHibernateSession.Current;
            if (context.OperationType != DomainOperationType.Query)
            {
                _transaction = Session.BeginTransaction();
            }
            base.Initialize(context);
        }

        protected override void ExecuteChangeSet(ChangeSet changeSet)
        {
            base.ExecuteChangeSet(changeSet);
            if (_transaction != null && _transaction.IsActive)
            {
                _transaction.Commit();
            }
        }

        protected override void Dispose(bool disposing)
        {
            Session.Dispose();
            base.Dispose(disposing);
        }
    }
}
